package com.deyuanyun.pic.settings.support.utils;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;

import org.apache.commons.beanutils.BeanUtils;
import org.apache.log4j.Logger;

import com.deyuanyun.pic.common.cache.TempStoreDataSupport;
import com.deyuanyun.pic.common.spring.SpringAppliction;
import com.deyuanyun.pic.common.util.ObjectUtil;
import com.deyuanyun.pic.common.util.StringUtils;
import com.deyuanyun.pic.settings.domain.base.Code;
import com.deyuanyun.pic.settings.domain.base.CodeExample;
import com.deyuanyun.pic.settings.mapper.base.CodeMapper;
import com.google.common.collect.ArrayListMultimap;
import com.google.common.collect.ListMultimap;

/**
 * @author chace.cai   xu
 * @description
 * 码表工具类
 * @date 2016/4/11
 */
public class BaseCodeUtils {
    static Logger logger= Logger.getLogger(BaseCodeUtils.class);
    private static ListMultimap<String,Code> menuListMultimap= ArrayListMultimap.create();
    private static final String CODE_DICT_IN_CACHE="APPLICATION.CODE_DICT_IN_CACHE";
    private static final String CODE_DICT_IN_CACHE_LIST="APPLICATION.CODE_DICT_IN_CACHE_LIST";


    public static synchronized void loadBaseCode(boolean refresh){
        ListMultimap<String,Code> listMultimap=TempStoreDataSupport.pullDataf(CODE_DICT_IN_CACHE);
        if (refresh||listMultimap==null||listMultimap.isEmpty()){
            CodeMapper codeMapper= SpringAppliction.getBean(CodeMapper.class);
            CodeExample example=new CodeExample();
            example.createCriteria().andDeletedEqualTo((byte) 0).andStateEqualTo((byte) 0);
            List<Code> codeList = codeMapper.selectByExample(example);
            menuListMultimap.clear();
            TempStoreDataSupport.removeDataf(CODE_DICT_IN_CACHE);
            for (Code code : codeList){
                menuListMultimap.put(code.getMajorCode(),code);
                //将短信参数单独处理
                if ("SMSCONFIG".equalsIgnoreCase(code.getMajorCode())&&
                        StringUtils.isNotEmpty(code.getMinorCode())
                        ){
                    String minroCode = code.getMinorCode();
                    if ("SMS_SEND_URL".equals(minroCode))
                        SMSUtils.SMS_SEND_URL=code.getName();
                    else if ("SMS_QUERY_URL".equals(minroCode))
                        SMSUtils.SMS_QUERY_URL=code.getName();
                    else if ("USERID".equals(minroCode))
                        SMSUtils.USERID=code.getName();
                    else if ("ACCOUNT".equals(minroCode))
                        SMSUtils.ACCOUNT=code.getName();
                    else if ("PWD".equals(minroCode))
                        SMSUtils.PWD=code.getName();
                    else if ("login_m".equals(minroCode))
                        SMSUtils.login_m=code.getName();
                    else if ("reg_m".equals(minroCode))
                        SMSUtils.reg_m=code.getName();
                    else if ("findPassWord_m".equals(minroCode))
                        SMSUtils.findPassWord_m=code.getName();
                    else if ("tryOut_m".equals(minroCode))
                        SMSUtils.tryOut_m=code.getName();
                }
            }
            TempStoreDataSupport.pushDataf(CODE_DICT_IN_CACHE,menuListMultimap);
        }

    }


    /**
     * 根据id得到码表中的名称
     *
     * @param id 码表Id
     * @return 码表的名称，如果没有该值，返回null对象
     */
    public static String getName(String id){
        Code c=TempStoreDataSupport.pullData(CODE_DICT_IN_CACHE_LIST+"_"+id);
        if (c!=null){
            return c.getShortName();
        }

        loadBaseCode(false);
        List<Code> codeList= TempStoreDataSupport.pullData(CODE_DICT_IN_CACHE_LIST);
        if (ObjectUtil.isEmptyAll(codeList)){
            codeList=new ArrayList<Code>(menuListMultimap.values());
            TempStoreDataSupport.pushDataByIdelTimeMinute(CODE_DICT_IN_CACHE_LIST,codeList,5);
        }
        for (Code code:codeList){
            if (StringUtils.isNotNullEmpty(id) && id.equals(code.getId())){

                TempStoreDataSupport.pushDataByIdelTimeMinute(CODE_DICT_IN_CACHE_LIST+"_"+id,code,5);
                return code.getShortName();
            }
        }

        return null;
    }


    /**
     * 根据id得到码表中的次要编号
     *
     * @param id 码表Id
     * @return 码表的次要编号，如果没有该值，返回null对象
     */
    public static String getMinorCode(String id){
        Code c=TempStoreDataSupport.pullData(CODE_DICT_IN_CACHE_LIST+"_"+id);
        if (c!=null){
            return c.getMinorCode();
        }

        loadBaseCode(false);
        List<Code> codeList= TempStoreDataSupport.pullData(CODE_DICT_IN_CACHE_LIST);
        if (ObjectUtil.isEmptyAll(codeList)){
            codeList=new ArrayList<Code>(menuListMultimap.values());
            TempStoreDataSupport.pushDataByIdelTimeMinute(CODE_DICT_IN_CACHE_LIST,codeList,5);
        }
        for (Code code : codeList){
            if (StringUtils.isNotNullEmpty(id) && id.equals(code.getId())){

                TempStoreDataSupport.pushDataByIdelTimeMinute(CODE_DICT_IN_CACHE_LIST+"_"+id,code,5);
                return code.getMinorCode();
            }
        }

        return null;
    }


    /**
     * 通过majorCode查找codeList
     * @param majorCode
     * @return
     */
    public static List<Code> getCodeList(String majorCode){
        loadBaseCode(false);
        List<Code> codeList=menuListMultimap.get(majorCode);
//        Collections.sort(codeList,codeSort() );

        return menuListMultimap.get(majorCode);
    }
    //将code进行排序
    private static Comparator codeSort(){
        return new Comparator<Code>() {
            @Override
            public int compare(Code o1, Code o2) {
                int o1v = o1.getSort();
                int o2v = o2.getSort();
                if (o1v>o2v){
                    return 1;
                }else if (o1v<o2v){
                    return -1;
                }else {
                    return 0;
                }

            }
        };
    }

    /**
     * 通过中文名和majorCode找到codeid
     * @param majorCode
     * @param name
     * @return
     */
    public static String getCodeId(String majorCode,String name){
        List<Code> codes=getCodeList(majorCode);
        for(Code info:codes){
            if(info.getShortName().equals(name))
            {
                return info.getId();
            }
        }
        return null;
    }


    /**
     * 将codeid字段转成codename
     * @param list
     * @param fields
     * @param <T>
     */
    public static<T> void convertId2CodeName(List<T> list,String[] fields) throws Exception{
        loadBaseCode(false);
        for (T t:list){
            for (String fName:fields){
                String id = BeanUtils.getProperty(t,fName);
                if (org.apache.commons.lang.StringUtils.isBlank(id)){
                    continue;
                }
                String name = getName(id);
                if (org.apache.commons.lang.StringUtils.isBlank(name)){
                    continue;
                }
                BeanUtils.setProperty(t,fName,name);
            }
        }

    }

}
